package cn.yh.register.cmn.service.impl;

import cn.yh.register.cmn.listener.DictListener;
import cn.yh.register.cmn.mapper.DictMapper;
import cn.yh.register.cmn.service.DictService;
import cn.yh.register.model.cmn.Dict;
import cn.yh.register.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    /**
     * 根据id查询子数据
     * @param id 字典id
     * @return  子数据列表
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        // 处理hasChildren属性  查询到数据 遍历出来设置到dict
        for (Dict dict : dictList) {
            dict.setHasChildren(this.hasChildren(dict.getId()));
        }
        return dictList;
    }

    //数据列表的导出功能 写入到Excel中  写
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //指定响应数据的格式
            response.setContentType("application/vnd.ms-excel");
            //防止乱码
            response.setCharacterEncoding("utf-8");
            //文件名
            String fileName = URLEncoder.encode( "数据字典","utf-8");
            //告诉浏览器以附件的方式打开（下载）
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            List<Dict> dictList = baseMapper.selectList(null);
            //需要接收的是DictEvo类型  但是原来查的是Dict类型  需要进行一个转换
            //转成vo对象  然后再转入dictEeVoList中
            List<DictEeVo> voList = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo vo = new DictEeVo();
                //两者的属性名是相同的  使用工具类直接转
                BeanUtils.copyProperties(dict,vo);
                voList.add(vo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(voList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //数据列表的导入功能
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据字典值和字典编码获取到字典名称
     * @param dictCode 字典编码
     * @param value    字典值
     * @return 字典名称
     */
    @Override
    public String getDataByValueAndDictCode(String dictCode, String value) {
        Dict dict;
        if (StringUtils.isEmpty(dictCode)){
            //如果根据字典值可以唯一确定一条数据
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value));
        }else if ("ROOT".equals(dictCode)){
            //一种特殊情况  作为“ROOT”的
            dict = this.getByDictCode(dictCode);
        } else {
            //根据字典值不能唯一确定一条数据，需要结合字典值和字典编码来查 拿这个作为父id再去查
            dict = this.getByDictCode(dictCode);
            // 把上面查出来的字典对象的 id 作为parentId, 结合字典值value一块儿查询
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getParentId, dict.getId())
                    .eq(Dict::getValue, value));
        }
        return dict.getName();
//        return dict.getName();
    }

    private Dict getByDictCode(String dictCode){
        return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
    }

    /**
     * 根据字典编码查询子数据
     * @param dictCode 字典编码
     * @return 子数据列表
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
        if (dict != null){
           return this.findChildData(dict.getId());
        }
        return null;
    }


    // 判断某个字典是否有子节点
    private Boolean hasChildren(Long id) {
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        return count > 0;
    }
}
